import {Vue} from 'vue-property-decorator';
import $http from "@/http";
import {ElForm} from "element-ui/types/form";
import {errorMsg, successMsg, warningMsg} from "@/utils/message";

/**
 * 新版本
 * 顶层处理类
 */
export default class BaseVue extends Vue {
    //表单数据
    public nowUpdateData: any = {};
    public nowUpdateDataIndex: any = 0;
    //表格数据
    public tableData: any = [];
    //表格已选中ids
    public tableSelectIds: any = [];
    //加载框
    public tableLoading: boolean = false;

    //查询条件
    public queryParam: any = {
        pageApi: "/page",
        size: 10,
        current: 1,
        currentSize: 0,
        pages: 0,
        total: 0,
    };

    //左侧详情抽屉
    public drawerInfo: any = {
        title: "",
        type: "info",
        size: 60,
        index: 0,
        direction: "ltr",
        isOpen: false,
        data: {},
        row: {},
    };


    //消息对话框
    public dialogMsg: any = {
        id: "",
        ids: [],
        title: "消息通知",
        content: "是否执行当前操作？",
        isOpen: false,
        open: false,
        type: "",
        param: {}//参数
    };

    //弹出层数据
    public dialogData: any = {
        id: "",
        ids: [],
        isOpen: false,
        isOpen1: false,
        title: "",
        type: "",
    };


    /**
     * 执行添加一条记录
     */
    baseStartInsert(url: any,  callback = (res: any) => {},formData: any = null, config: any = null): any {
        let data = {};
        if (formData) {
            data = formData;
        }
        (this.$refs.mFormData as ElForm).validate((valid: boolean) => {
            if (valid) {
                return $http.post(url, data, config)
                    .then((res: any) => {
                        if (res.success) {
                            successMsg("操作成功");
                            this.dialogData.isOpen = false;
                            this.tableSelectIds = [];
                            this.basePage(null);
                            callback(res);
                            return res;
                        }
                        callback(res);
                    });
            } else {
                errorMsg("表单内容填写错误，请检查！")
            }
        })
    }

    /**
     * 执行批量删除
     */
    public baseStartDelBatch(url: any, config: any = null): any {
        return $http.post(url, this.tableSelectIds, config)
            .then((res: any) => {
                if (res.success) {
                    setTimeout(() => {
                        successMsg("操作成功");
                        this.dialogMsg.isOpen = false;
                        this.tableSelectIds = [];
                        this.basePage(null);
                    }, 100);
                    return res;
                }
            });
    }

    /**
     * 执行修改数据
     */
    public baseStartUpdate(
        url: any,
        callback: any = (res: any) => {
        },
        formData: any = null,
        config: any = null): any {
        let data = {};
        if (formData) {
            data = formData;
        }
        (this.$refs.mFormData as ElForm).validate((valid: boolean) => {
            if (valid) {
                return $http.post(url, data, config)
                    .then((res: any) => {
                        if (res.success) {
                            successMsg("操作成功");
                            this.dialogData.isOpen = false;
                            this.tableSelectIds = [];
                            this.basePage(null);
                        }
                        callback(res);
                    });
            } else {
                errorMsg("表单内容填写错误，请检查！")
            }
        })
    }

    /**
     * 执行查询分页
     */
    public basePage(pageUpdate: any, query: any = null): any {
        if (query) {
            this.queryParam = query
        }
        this.tableLoading = true;
        if (pageUpdate) {
            this.queryParam.size = pageUpdate.pageSize;
            this.queryParam.current = pageUpdate.currentPage;
        }
        return $http.post(this.queryParam.pageApi, this.queryParam)
            .then((res: any) => {
                if (res.success) {
                    this.tableData = res.data['records'];
                    if (this.tableData.length == 0 && this.queryParam.current > 0) {
                        this.queryParam.current = ((this.queryParam.current * 1) - (1 * 1));
                        this.basePage(null);
                        return res;
                    }
                    this.queryParam.size = res.data['size'];
                    this.queryParam.current = res.data['current'];
                    this.queryParam.currentSize = res.data['records'].length;
                    this.queryParam.pages = res.data['pages'];
                    this.queryParam.total = res.data['total'];
                    this.tableLoading = false;
                    return res;
                }
            });
    }


    /**
     * 展示数据
     * @param title 标题
     * @param type 类型
     * @param index 数据位置
     * @param row 展示数据内容
     */
    public baseShowDataDialog(title: any = "详情", type: any = "info", index: any = 0, row: any = {}) {
        this.dialogData.title = title;
        this.dialogData.type = type;
        this.dialogData.index = index;
        this.dialogData.isOpen = true;
        this.nowUpdateData = JSON.parse(JSON.stringify(row));
        this.baseCleanValidate();

    }

    /**
     * 左侧抽屉-展示数据
     * @param title 标题
     * @param index 数据位置
     * @param row 展示数据内容
     */
    public baseShowDrawerInfo(title: any = "详情", index: any = 0, row: any = {}) {
        this.drawerInfo.title = title;
        this.drawerInfo.index = index;
        this.drawerInfo.row = row;
        this.drawerInfo.isOpen = true;
        this.drawerInfo.data = JSON.parse(JSON.stringify(row));
    }

    /**
     * 展示删除 MessageDialog
     */
    public baseShowDelete(index: any, row: any, title: any, type: any, content: any = null) {
        this.dialogMsg.type = type;
        this.dialogMsg.title = title;
        this.tableSelectIds = [];
        this.tableSelectIds.push(row.id);
        this.dialogMsg.content = "确认删除 " + this.tableSelectIds.length + " 条数据？";
        if (content != null) {
            this.dialogMsg.content = content.toString();
        }
        this.dialogMsg.isOpen = true;
    }

    /**
     * 展示批量删除 MessageDialog
     */
    public baseShowDeleteBatch(title: any = "通知") {
        if (this.tableSelectIds.length > 0) {
            this.dialogMsg.type = "deleteBatch";
            this.dialogMsg.title = title;
            this.dialogMsg.content = "确认删除 " + this.tableSelectIds.length + " 条数据？";
            this.dialogMsg.isOpen = true;
        } else {
            warningMsg("至少选择一条数据.");
        }
    }

    /**
     * 还原修改数据
     */
    public baseCancelUpdate() {
        this.baseCleanValidate()
    }

    /**
     * 复选框Change事件
     */
    public baseSelectionChange(val: Array<any>) {
        this.tableSelectIds = [];
        val.filter((it) => {
            this.tableSelectIds.push(it.id)
        });
    }

    /**
     * 清除表单验证
     */
    public baseCleanValidate() {
        if ((this.$refs.mFormData as ElForm)) {
            (this.$refs.mFormData as ElForm).clearValidate();
        }
        setTimeout(() => {
            if ((this.$refs.mFormData as ElForm)) {
                (this.$refs.mFormData as ElForm).clearValidate();
            }
        }, 200);
    }

    public msgBox(title: any = "通知", message: any = "是否执行操作？",
                  funOk: any = () => {
                  },
                  funCancel: any = () => {
                  },
                  type: any = "warning", btnOkText: any = "确定", btnCancelText: any = "取消") {
        this.$confirm(message, title, {
            confirmButtonText: btnOkText,
            cancelButtonText: btnCancelText,
            dangerouslyUseHTMLString: true,
            type: type,
        }).then(() => {
            funOk();
        }).catch(() => {
            funCancel();
        });
    }

    public msgBoxInput(title: any = "通知", message: any = "是否执行操作？",
                       funOk: any = (value: any) => {
                       },
                       funCancel: any = () => {
                       },
                       type: any = "warning", btnOkText: any = "确定", btnCancelText: any = "取消") {
        this.$prompt(message, title, {
            confirmButtonText: btnOkText,
            cancelButtonText: btnCancelText,
        }).then((val: any) => {
            funOk(val.value);
        }).catch(() => {
            funCancel();
        });
    }

    /**
     * post 请求
     *
     * @param url 请求地址
     * @param param 请求参数 {}
     * @param config 配置 {}
     * @param refresh 请求完成后是否刷新界面
     */
    public basePost(url: any, param: any = {}, config: any = null, refresh: boolean = true) {
        return $http.post(url, param, config)
            .then((res: any) => {
                if (res.success) {
                    if (refresh) {
                        successMsg("操作成功");
                        this.dialogData.isOpen = false;
                        this.tableSelectIds = [];
                        this.dialogMsg.isOpen = false;
                        this.basePage(null);
                    }
                }
                return res;
            });
    }

    /**
     * 重置查询条件
     */
    public baseResetQuery() {
        let parse = JSON.parse(JSON.stringify(this.queryParam));
        this.queryParam = {
            pages: parse.pages,
            total: parse.total,
            current: parse.current,
            size: parse.size,
        };
    }

}
